import * as fs from "fs";
import { createProxyMiddleware } from "http-proxy-middleware";
import { resolve, dirname, join } from "path";
import express from "express";
import { loadEnv as _loadEnv } from "vite";
import { fileURLToPath } from "url";

const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const client = join(root, "./dist/client");
const server = join(root, "./dist/server");
const app = express();

const loadEnv = () => {
  const i = process.argv.findIndex((it) => it === "--mode" || it === "-m");
  const mode = i < 0 ? "development" : process.argv[i + 1] || "development";
  return _loadEnv(mode, root);
};

const env = loadEnv();
console.log({ env });
app
  .use(express.static(client, { index: false }))
  .use(
    "/api",
    createProxyMiddleware({
      target: env.VITE_API_BASE_URL, // target host
      changeOrigin: true, // needed for virtual hosted sites
      ws: true,
    })
  )
  .use(async (req, res) => {
    try {
      const url = req.originalUrl;

      const template = fs.readFileSync(resolve(client, "index.html"), "utf-8");

      const { render } = await import(resolve(server, "./entry-server.js"));

      const manifest = await import(
        resolve(client, "./.vite/ssr-manifest.json"),
        {
          assert: { type: "json" },
        }
      );

      const ctx = {};

      const html = await render(url, manifest, ctx, template);

      res.set({ "Content-Type": "text/html" });

      res.end(html);
    } catch (e) {
      console.error(e);
      let message =
        typeof e.stack === "string"
          ? e.stack
          : typeof e.message == "string"
          ? e.message
          : "未知错误，请查看node debugger";
      res.set({ "Content-Type": "text/html" }).end(message);
    }
  })

  .listen(9030, () => {
    console.log("look at http://localhost:9030");
  });
